package sf.callback.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import sf.callback.common.Echo;
import sf.callback.common.Payload;
import sf.core.entity.TfImage;
import sf.core.entity.TuAdmin;
import sf.core.entity.TuCoach;
import sf.core.entity.TuGym;
import sf.core.entity.TuMember;
import sf.core.mapper.TfImageMapper;
import sf.core.mapper.TuAdminMapper;
import sf.core.mapper.TuCoachMapper;
import sf.core.mapper.TuGymMapper;
import sf.core.mapper.TuMemberMapper;
import sf.core.service.StorageService;

@Controller
@RequestMapping("/qiniu")
@ResponseBody
public class QiniuController {

	private Logger logger = LoggerFactory.getLogger(QiniuController.class);

	@Resource
	TfImageMapper imageMapper;

	@Resource
	TuMemberMapper memberMapper;

	@Resource
	TuCoachMapper coachMapper;

	@Resource
	TuGymMapper gymMapper;

	@Resource
	TuAdminMapper adminMapper;

	@RequestMapping(value = "/image")
	public Echo uploadImage(@RequestParam String key, @RequestParam Integer type, @RequestParam int xid) {

		String fetchKey = String.format("%s_%s_%s", type, xid, key);
		logger.error(key);
		TfImage image = new TfImage();
		image.setType(type.byteValue());
		image.setXid(xid);
		image.setUrl(StorageService.DOMAIN_QINIU_MEDIA + fetchKey);
		imageMapper.insert(image);
		Echo echo = new Echo();
		echo.setKey(fetchKey);
		echo.setPayload(new Payload(image));
		return echo;
	}

	@RequestMapping(value = "/avatar")
	public Echo uploadAvatar(@RequestParam String key, @RequestParam char type, @RequestParam int xid) {

		String fetchKey = String.format("%s_%s_%s", type, xid, key);
		logger.error(fetchKey);
		String url = StorageService.DOMAIN_QINIU_MEDIA + fetchKey;
		switch (type) {
		case StorageService.TYPE_MEMBER:
			TuMember member = memberMapper.selectByPrimaryKey(xid);
			member.setAvatar(url);
			memberMapper.updateByPrimaryKeySelective(member);
			break;
		case StorageService.TYPE_COACH:
			TuCoach coach = coachMapper.selectByPrimaryKey(xid);
			coach.setAvatar(url);
			coachMapper.updateByPrimaryKeySelective(coach);
			break;
		case StorageService.TYPE_GYM:

			TuGym gym = gymMapper.selectByPrimaryKey(xid);
			gym.setLogo(url);
			gymMapper.updateByPrimaryKeySelective(gym);
			break;
		case StorageService.TYPE_ADMIN:
			TuAdmin admin = adminMapper.selectByPrimaryKey(xid);
			admin.setAvatar(url);
			adminMapper.updateByPrimaryKeySelective(admin);
			break;
		default:
			break;
		}
		Echo echo = new Echo();
		echo.setKey(fetchKey);
		Map<String, String> data = new HashMap<String, String>();
		data.put("url", url);
		echo.setPayload(new Payload(data));
		return echo;
	}

}
